<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    title="插入公式"
    append-to-body
    width="600px"
    @close="$emit('close')"
  >
    <div ref="editorContainer" style="height: 300px; margin: -20px 0"></div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'Wiris',
  data() {
    return {
      dialogVisible: false,
      wirisEditor: null
    }
  },
  created() {
    if (!window.com) {
      const wirisScript = document.createElement('script')
      wirisScript.src = '//equation.kaoyanvip.cn/wiris/editor.js'
      document.querySelector('body').appendChild(wirisScript)
      // eslint-disable-next-line
      console.log('loading wiris script')
    }
  },
  methods: {
    open(alt = '') {
      this.dialogVisible = true
      this.$nextTick(() => {
        if (!this.wirisEditor) {
          this.wirisEditor = window.com.wiris.jsEditor.JsEditor.newInstance({
            fontSize: '32px',
            language: 'zh',
            detectHand: false
          })
          this.wirisEditor.insertInto(this.$refs.editorContainer)
        }
        this.wirisEditor.setMathMLWithCallback(alt, () => {})
      })
    },
    submit() {
      var value = this.wirisEditor.getMathML()
      this.$emit('change', value)
      this.dialogVisible = false
    },
    close() {
      this.$emit('close')
      this.dialogVisible = false
    }
  }
}
</script>
